package com.google.code.slumdog.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.log4j.Logger;

/**
 * Poll historical result from an URL link. It establish a connection to
 * retrieve html content of the target webpage, and possess the content in a
 * String.
 * 
 * @author Zhihai Zhang
 */
public class HistoricalResultPoller implements Poller {

	private String targetUrl;
	private static Logger logger = Logger.getLogger(HistoricalResultPoller.class);
	private String content;

	public HistoricalResultPoller() {
		targetUrl = null;
		content = null;
	}

	public HistoricalResultPoller(String targetUrl) {
		this.targetUrl = targetUrl;
		content = null;
	}

	@Override
	public void process() {
		URL url;
		InputStream is = null;
		InputStreamReader in = null;
		BufferedReader br = null;
		String htmlContent = "";
		logger.info(String.format("Start processing onlineSource from given URL: %s", targetUrl));

		try {
			url = new URL(targetUrl);
			is = url.openStream();
			in = new InputStreamReader(is);
			br = new BufferedReader(in);
			String s = null;
			while ((s = br.readLine()) != null) {
				htmlContent += s;

			}

		} catch (MalformedURLException e) {
			logger.debug("No valid protocal found in target URL, or it cannot be parsed.");
			e.printStackTrace();
		} catch (IOException e) {
			logger.debug("Cannot open stream from target URL");
			e.printStackTrace();
		} finally {
			try {
				is.close();
				in.close();
				br.close();
			} catch (IOException e) {
				logger.debug("InputStream cannot be closed");
			}
		}
		this.content = htmlContent;
	}

	public String getTargetUrl() {
		return targetUrl;
	}

	public void setTargetUrl(String targetUrl) {
		this.targetUrl = targetUrl;
	}
	public String getContent() {
		return this.content;
	}

	@Override
	public void setContent(String content) {
		this.content = content;
	}
}
